package com.lz.security.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.databind.util.BeanUtil;
import com.lz.enums.DelEnum;
import com.lz.pojo.SysPermission;
import com.lz.pojo.SysRole;
import com.lz.pojo.SysUser;
import com.lz.security.pojo.LoginUser;
import com.lz.service.SysPermissionService;
import com.lz.service.SysRoleService;
import com.lz.service.SysUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * 从数据库查询用户的用户名和密码
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysRoleService sysRoleService;
    @Autowired
    private SysPermissionService sysPermissionService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //根据用户名查询用户
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUser::getMobile, username);
        wrapper.eq(SysUser::getDel, DelEnum.ENTER_DEL_NO.getStatus());
        SysUser sysUser = sysUserService.getOne(wrapper);
        if (sysUser == null){
            throw new UsernameNotFoundException("用户不存在");
        }

        LoginUser loginUser = new LoginUser();
        //复制对象的属性值
        BeanUtils.copyProperties(sysUser,loginUser);
        //查询当前登陆用户的权限
        //1.根据用户id查询角色数据
        List<SysRole> roleList = sysRoleService.listByUserId(sysUser.getId());
        List<SysPermission> permissionList = sysPermissionService.listByUserId(sysUser.getId());
        loginUser.setRoleNameList(roleList.stream().map(item -> item.getRolename()).collect(Collectors.toList()));
        loginUser.setPercodeList(permissionList.stream().map(SysPermission::getPercode).collect(Collectors.toList()));
        return loginUser;
    }
}
